import { ref, reactive, computed } from 'vue'
import layoutCompatible from '../layoutCompatible'
import type { PageLayouts, PageComponentsOption,ShareComponentsOption , PopAdvertisingComponentsOption } from '@/common/request/api'
import type { AppContext } from '@/common/hooks'
import type {TabbarPageItem} from '@/common/stores/init'
// #ifdef PRIVATE || SUBSCRIPTION
import { mpShareInit } from '@/common/utils'
import type {  MpShare } from '@/common/utils'
import {getShareLink } from '@/common/wxInit'
// #endif

export type AppComponentsList = Array<{
	key: string,
	components: string,
	option: Record<any, any>
}>

type newPopAdvertisingComponentsOption = PopAdvertisingComponentsOption & { showDate: string, frequency: number }


export const useLayout = (ctx: AppContext) => {
	const layoutPageTitle = ref('')
	const componentsList = reactive<AppComponentsList>([])
	const pageOption = ref<Partial<PageComponentsOption>>({})
	// 是否使用默认的分享参数，如果获取到的页面装修数据中配置了分享参数，则isDefaultShare为false
	const isDefaultShare = ref(true)

	const pageStyle = computed(() => {
		let data: Record<string, any> = {}
		if (pageOption.value.styleType === '1') {
			data = {
				padding: `${(pageOption.value.paddingTop || 0) * 2}rpx ${(pageOption.value.paddingX || 0) * 2}rpx  ${(pageOption.value.paddingBottom || 0) * 2}rpx ${(pageOption.value.paddingX || 0) * 2}rpx`
			}
		}
		if (pageOption.value.type === '1') {
			return { ...data, backgroundColor: pageOption.value.backgroundColor }
		}
		if (pageOption.value.type === '2' && pageOption.value.backgroundUrl || customPageBgImgUrl.value) {
			return {
				...data,
				backgroundImage: `url(${ctx.$fullLink(customPageBgImgUrl.value || pageOption.value.backgroundUrl || '')})`,
				backgroundRepeat: 'no-repeat',
				backgroundSize: customPageBgImgUrl.value ? `100% ${customPageBgImgHeight.value}px` : '100%',
				transition: customPageBgImgUrl.value ? 'background 0.6s ease-in-out' : ''
			}
		}
	})

	const mpShare = ref< MpShare | {}>({})


	const customPageBgImgUrl = ref('')
	const customPageBgImgHeight = ref(0)
	const setPageBackgroundImage = (data: { url: string, height: number }) => {
		customPageBgImgUrl.value = data.url
		customPageBgImgHeight.value = data.height
	}

	const advertisingSetting = ref<newPopAdvertisingComponentsOption | { openAd: boolean }>({ openAd: false })


	const setPageOption = (data: TabbarPageItem, isRefresh = false,layoutPageParams = {}) => {

		uni.setNavigationBarTitle({
			title: data?.pageName || '\u200e'
		})
		layoutPageTitle.value = data?.pageName || '\u200e'
		const pageLayout = data?.text?.pageLayout || data?.pageLayout
		if (!pageLayout) return
		let oldLength = 0
		if (isRefresh) {
			oldLength = componentsList.length
		} else {
			componentsList.splice(0);
		}

		const arr = ['page', 'share', 'popAdvertising']
		const pageLayouts = JSON.parse(pageLayout) as PageLayouts
		// 使用当前时间作为本次组件item的键值，防止刷新数据时，组件item的键值与上次不变，导致组件没有重新渲染
		const nowDate = new Date().getTime()
		// 组件列表替换索引
		let componentsListIndex = 0
		pageLayouts.forEach((item, index) => {
			if (arr.includes(item.componentsName)) {
				switch (item.componentsName) {
					case 'page':
						pageOption.value = item as PageComponentsOption
						if (item.headerColor) {
							// this.$emit('setPageHeaderColor', item.headerColor, item.headerTextColor || '#000')
							let headerColor = (item as PageComponentsOption).headerColor
								.replace(/rgba?\(/, '')
								.replace(/\)/, '')
								.replace(/[\s+]/g, '')
								.split(',')

							let a = parseFloat(headerColor[3] || '1'),
								r = Math.floor(a * parseInt(headerColor[0]) + (1 - a) * 255),
								g = Math.floor(a * parseInt(headerColor[1]) + (1 - a) * 255),
								b = Math.floor(a * parseInt(headerColor[2]) + (1 - a) * 255)
							uni.setNavigationBarColor({
								frontColor: item.headerTextColor,
								backgroundColor: `#${('0' + r.toString(16)).slice(-2)}${('0' + g.toString(16)).slice(-2)}${('0' + b.toString(16)).slice(-2)}`
							})
						} else {
							// this.$emit('setPageHeaderColor', '#fff', item.headerTextColor || '#000')
						}
						break
						case 'share':
						
							if (item.type === '1') {
								isDefaultShare.value = false
								let { title, desc, imgUrl } = item as ShareComponentsOption 
						
								let _mpShare: MpShare = {
									title, // 默认为小程序名称
									desc,
									path: '', // 默认为当前页面路径
									imageUrl: imgUrl, // 默认为当前页面的截图,
									appParams: layoutPageParams
								}
								// #ifdef PRIVATE || SUBSCRIPTION
								_mpShare = {
									title,
									desc,
									link: getShareLink(),
									imgUrl
								}
						
								mpShareInit(_mpShare)
								// #endif
								uni.$endless.mpShare = _mpShare
								mpShare.value = _mpShare
							} else {
								// #ifdef PRIVATE || SUBSCRIPTION
								let _mpShare = {
									title: '',
									link: getShareLink(),
									imgUrl: ''
								}
								uni.$endless.mpShare = _mpShare
								mpShareInit(_mpShare)
								mpShare.value = _mpShare
								// #endif
							}
						
						break
						case 'popAdvertising':
							if (item.openAd ) {
								let _advertisingSetting = uni.getStorageSync(`advertisingSetting-${data.pageId}`)
								let advertisingImage = _advertisingSetting?.imgUrl
								if (item.showType == 1) {
									// 仅首次显示广告
									if (advertisingImage !== item.imgUrl) {
										advertisingSetting.value = item as newPopAdvertisingComponentsOption
										uni.setStorageSync(`advertisingSetting-${data.pageId}`, item)
									}
								} else {
									// 每日固定次数显示广告
									let frequency = _advertisingSetting?.frequency || 0
									let [oldDate, newDate] = [_advertisingSetting.showDate, new Date().toLocaleDateString()]
									if (oldDate !== newDate || advertisingImage !== item.imgUrl) {
										//  判断上一次显示广告的日期是不是当天,不是则将frequency清零
										frequency = 0
									}
									if (frequency < item.count) {
										frequency++
										advertisingSetting.value = {
											...item,
											frequency,
											showDate: newDate
										} as newPopAdvertisingComponentsOption
										uni.setStorageSync(`advertisingSetting-${data.pageId}`, advertisingSetting.value)
									}
								}
							}
						
						break
				}
			}else{
				if (!item._componentsHidden) {
					componentsList.splice(componentsListIndex,1,{
						key: `${index}-${item.componentsName}-${nowDate}`,
						components: item.componentsName,
						option: layoutCompatible(item.componentsName, item)
					})
					componentsListIndex++
				}
			}
			
			if(oldLength && oldLength > pageLayouts.length){
				componentsList.splice(pageLayouts.length)
			}
			
			// if(orderIcon){
			// 	// this.$store.commit('setOrderIconText', orderIcon.option.titleList)
			// }

		})
		let orderIcon = componentsList.find(item => item.components === 'orderIcon')
		return orderIcon
	}


	return {
		layoutPageTitle,
		componentsList,
		pageStyle,
		setPageBackgroundImage,
		advertisingSetting,
		mpShare,
		setPageOption,
		isDefaultShare
	}
}